﻿const http = require('http');
const chalk = require('chalk');
const path = require('path');
const config = require('./config/defaultConfig.js');
const readFile = require('./helper/readFile.js');
const querystring = require('querystring');
const util = require('util');
const url = require('url');
const requestExp = require('./method/index')

const {
    service
} = config;

class Response {
    constructor(data, code, msg) {
        this.response = JSON.stringify({
            data,
            code,
            msg
        })
    }

    static of (data = '请求错误', code = 0, msg = 'success') {
        const {
            response
        } = new Response(data, code, msg);
        return response;

    }
}

var server = http.createServer(function (req, res) {
    const filePath = path.join(config.root, req.url)
    if (filePath === '/root/soft/anydoor/src/') {
        res.writeHead(301, {
            'Location': `http://${config.hostname}:${config.port}/public`
        });
        console.log(res._header);
        res.end();
        return;
    }
    console.info("path", `${chalk.green(filePath)}`)
    readFile(req, res, filePath)
});

const apiService = http.createServer(function (req, res) {
    const {
        method
    } = req;
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.setHeader('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

    res.writeHead(200, {
        'Content-Type': 'application/json'
    });

    if (method === 'OPTIONS') {
        res.end();
        return;
    };

    const endWith = data => res.end(Response.of(data));

    if (method === 'GET') {
        const {
            pathname,
            query
        } = url.parse(req.url, true);
        const reslut = requestExp('GET', pathname, query);
        endWith(reslut)
    }

    if (method === 'POST') {
        var post = '';

        // 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
        req.on('data', function (chunk) {
            post += chunk;
        });

        // 在end事件触发后，通过querystring.parse将post解析为真正的POST请求格式，然后向客户端返回。
        req.on('end', function () {
            post = JSON.parse(post);
            const {
                pathname
            } = url.parse(req.url, true);

            const reslut = requestExp('POST', pathname, post);
            endWith(post)
        });
    }

    endWith();

});


server.listen(config.port, config.hostname, () => {
    var addr = `http://${config.hostname}:${config.port}`;
    console.info(`listenning in:${chalk.green(addr)}`);
})

apiService.listen(service.port, service.hostname, () => {
    var addr = `http://${service.hostname}:${service.port}`;
    console.info(`listenning in:${chalk.red(addr)}`);
})